package com.kds.fxtool.config;

import com.kds.fxtool.feign.UpdateServiceClient;
import feign.Feign;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.okhttp.OkHttpClient;
import feign.slf4j.Slf4jLogger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.kds.fxtool")
public class ApplicationConfig {
    
    private static AnnotationConfigApplicationContext context;
    
    public static void initialize() {
        if (context == null) {
            context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        }
    }
    
    public static <T> T getBean(Class<T> beanClass) {
        if (context == null) {
            initialize();
        }
        return context.getBean(beanClass);
    }
    
    public static void close() {
        if (context != null) {
            context.close();
            context = null;
        }
    }
    
    @Bean
    public UpdateServiceClient updateServiceClient() {
        return Feign.builder()
                .client(new OkHttpClient())
                .encoder(new GsonEncoder())
                .decoder(new GsonDecoder())
                .logger(new Slf4jLogger(UpdateServiceClient.class))
                .logLevel(feign.Logger.Level.FULL)
                .target(UpdateServiceClient.class, AppConfig.UPDATE_URL);
    }
}